# coding=UTF-8

import sys
import os
try:
    import Image # request PIL 1.1.6
    import ImageOps 
except ImportError:
    print 'PIL 1.1.6 required'    
    
class Thumbnail:
    def __init__(self,orgImg,destDir,destName=None): #  orginal img filename with full-path
        self.org = orgImg
        self.destDir = destDir
        self.destName = destName
        self.scaleWidth = 225.0
        self.scaleHeigth = -1.0
        self.dest = self.getDestImg(self.org,self.destDir)
        self.file = Image.open(self.org)
        self.quality = Image.ANTIALIAS
    
    def getDestImg(self,org,destDir):
        filename = os.path.basename(org)
        if self.destName != None:
            return destDir+'/'+self.destName
        return destDir+'/'+filename
        
    def create(self, crop=False):
        '''call pil to resize the img to fixed width and heigth'''
        cropHeigth = 300
        orgWidth, orgHeigth = self.getOrginalSize()
        if orgWidth < self.scaleWidth:
            self.scaleWidth = orgWidth
            self.scaleHeigth = orgHeigth
        else:
            ratio = orgWidth / self.scaleWidth
            self.scaleHeigth = orgHeigth / ratio
        # call pil to resize the image
        size = int(self.scaleWidth), int(self.scaleHeigth)
        self.file.thumbnail(size,self.quality)
        # crop
        if crop == True:
            if cropHeigth > self.scaleHeigth:
                cropHeigth = self.scaleHeigth
            box = (0,0,int(self.scaleWidth),int(cropHeigth))
            region = self.file.crop(box)
            #region = region.transpose(Image.ROTATE_180)
            img = Image.new(self.file.mode,box[2:])
            img.paste(region, box)
#            print 'crop>>',box
            try:
                img.save(self.dest,'JPEG')
            except IOError, err:
                if img.mode != "RGB":
                    img = img.convert("RGB")
                    img.save(self.dest,'JPEG')
            try:
                # 120x120
                i2 = ImageOps.fit(self.file, (120, 120))
                smallcrop = self.dest.replace('crop_', 'cropsmall_')
                i2.save(smallcrop)
            except Exception, ex:
                pass

            return int(self.scaleWidth),int(cropHeigth)
            
        self.file.save(self.dest,'JPEG')
        return int(self.scaleWidth), int(cropHeigth)
        
    def reduce(self, scaleWidth=500):
        '''call pil to resize the img to fixed width and heigth'''
        
        orgWidth, orgHeigth = self.getOrginalSize()
        if orgWidth < scaleWidth:
            return
        else:
            ratio = orgWidth / self.scaleWidth
            self.scaleHeigth = orgHeigth / ratio
            # call pil to resize the image
            size = int(self.scaleWidth), int(self.scaleHeigth)
            self.file.thumbnail(size,self.quality)
                
            self.file.save(self.dest,'JPEG')
        
    def getOrginalSize(self):
        '''  call pil to read the width and heigth  '''
        return self.file.size
        
def createThumbnail(fname):
#    print 'creating thumbnail for',fname
    thumbnailPath = os.path.abspath(os.path.dirname(fname))
    destName = os.path.basename(fname)
    try:
        thumbnail = Thumbnail(fname, thumbnailPath, destName)
        thumbnail.create(False)
    except Exception, ex:
        print ex
#    print 'thumbnail created.'
    
def createThumbnailForDir(dirname):
#    print 'creating thumbnail for images in ', dirname
    for fname in os.listdir(dirname):
        createThumbnail(os.path.join(dirname, fname))
#    print 'done'
        
def test():
    org = 'c:/ray.jpg'
    destDir = 'c:/bea/'
    destName='crop2_ray.jpg'
    thumbnail = Thumbnail(org,destDir,destName)
    thumbnail.create(False)
    
def test2():
    org = 'c:/111.jpg'
    dest = 'c:/222.jpg'
    f = Image.open(org).save(org)
    
if __name__ == '__main__':
    a = Thumbnail('c:/dx/mpl-studios-ava-cup-of-tea-72.jpg', 'C:/dx/', 'crop_mpl-studios-ava-cup-of-tea-72.jpg')
    a.create(True)
#    test2()
#    createThumbnailForDir('c:/images')
#    i = Image.open('c:/mpl-studios-ava-cup-of-tea-7.jpg')
#    i2 = ImageOps.fit(i, (120, 120))
#    i2.save('c:/mpl-studios-ava-cup-of-tea-73.jpg')
##    print i.size
##    i = i.resize(i.size(), )
#    i.save('c:/mpl-studios-ava-cup-of-tea-72.jpg')
